package com.exampletest.controller;

import com.exampletest.model.Dynamic;
import com.exampletest.service.DynamicService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;

@RestController
@RequestMapping("/dynamic")
public class DynamicController {

    @Autowired
    private DynamicService dynamicService;

    // 图片上传目录
    private static final String UPLOAD_DIR = "src/main/resources/static/uploads/";

    // 发布动态
    @PostMapping("/publish")
    public Map<String, Object> publishDynamic(MultipartHttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 1. 解析JSON格式的文本数据（dynamic参数）
            String dynamicJson = request.getParameter("dynamic");
            System.out.println("接收到的dynamicJson：" + dynamicJson);
            if (dynamicJson == null || dynamicJson.isEmpty()) {
                result.put("code", 400);
                result.put("message", "缺少动态数据");
                return result;
            }
            Dynamic dynamic = objectMapper.readValue(dynamicJson, Dynamic.class);

            // 2. 解析封面图片（coverUrl参数）
            MultipartFile coverFile = request.getFile("coverUrl");

            // 3. 设置发布时间和状态（与编辑页一致）
            dynamic.setPublishTime(new Date());
            dynamic.setStatus(0); // 强制状态为0
            // 4. 处理封面图片上传
            if (coverFile != null && !coverFile.isEmpty()) {
                String fileName = UUID.randomUUID() + "." +
                        coverFile.getOriginalFilename().split("\\.")[1];
                Path uploadPath = Paths.get(UPLOAD_DIR);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                Path filePath = uploadPath.resolve(fileName);
                Files.copy(coverFile.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                dynamic.setCoverUrl("/uploads/" + fileName);
            }

            // 5. 保存到数据库
            int insertResult = dynamicService.publishDynamic(dynamic);
            if (insertResult > 0) {
                result.put("code", 200);
                result.put("message", "发布成功");
            } else {
                result.put("code", 500);
                result.put("message", "发布失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "发布失败: " + e.getMessage());
        }
        return result;
    }

    // 编辑动态（更新作者、简介、发布时间，状态设为1）
    @PostMapping("/edit")
    public Map<String, Object> editDynamic(
            @RequestPart("dynamic") Dynamic dynamic,
            @RequestPart(value = "coverUrl", required = false) MultipartFile coverFile) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 强制设置状态为1
            dynamic.setStatus(0);
            // 编辑时更新发布时间为当前时间
            dynamic.setPublishTime(new Date());

            // 处理封面图片
            if (coverFile != null && !coverFile.isEmpty()) {
                String fileName = UUID.randomUUID() + "." +
                        coverFile.getOriginalFilename().split("\\.")[1];
                Path uploadPath = Paths.get(UPLOAD_DIR);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                Path filePath = uploadPath.resolve(fileName);
                Files.copy(coverFile.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                dynamic.setCoverUrl("/uploads/" + fileName);
            }

            // 执行更新
            int updateResult = dynamicService.editDynamic(dynamic);
            if (updateResult > 0) {
                result.put("code", 200);
                result.put("message", "编辑成功");
            } else {
                result.put("code", 500);
                result.put("message", "编辑失败，数据未更新");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "编辑失败: " + e.getMessage());
        }
        return result;
    }

    // 富文本图片上传
    @PostMapping("/upload-image")
    public Map<String, Object> uploadImage(@RequestParam("upload") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (file != null && !file.isEmpty()) {
                String fileName = UUID.randomUUID() + "." +
                        file.getOriginalFilename().split("\\.")[1];
                Path uploadPath = Paths.get(UPLOAD_DIR);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                Path filePath = uploadPath.resolve(fileName);
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                result.put("url", "/uploads/" + fileName);
                result.put("uploaded", 1);
            } else {
                result.put("uploaded", 0);
                result.put("error", Map.of("message", "未选择图片"));
            }
        } catch (Exception e) {
            result.put("uploaded", 0);
            result.put("error", Map.of("message", "上传失败: " + e.getMessage()));
        }
        return result;
    }

    // 获取动态详情（含作者、简介）
    @GetMapping("/detail")
    public Map<String, Object> getDynamicDetail(@RequestParam("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        Dynamic dynamic = dynamicService.getDynamicById(id);
        if (dynamic != null) {
            result.put("code", 200);
            result.put("data", dynamic);
        } else {
            result.put("code", 500);
            result.put("message", "查询失败");
        }
        return result;
    }

    // 其他接口（删除、列表、审核）保持不变
    @PostMapping("/delete")
    public Map<String, Object> deleteDynamic(@RequestParam("dynamicId") Long id) {
        Map<String, Object> result = new HashMap<>();
        int deleteResult = dynamicService.deleteDynamic(id);
        if (deleteResult > 0) {
            result.put("code", 200);
            result.put("message", "删除成功");
        } else {
            result.put("code", 500);
            result.put("message", "删除失败");
        }
        return result;
    }

    @GetMapping("/list")
    public Map<String, Object> getDynamicList(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(value = "author", defaultValue = "") String author,
            @RequestParam(value = "status", required = false) Integer status) {  // 接收status参数
        Map<String, Object> result = new HashMap<>();
        // 计算偏移量
        int offset = (page - 1) * pageSize;
        // 调用服务层方法时传入status参数，在SQL中添加筛选条件
        List<Dynamic> dynamics = dynamicService.getDynamicList(keyword, author, status, offset, pageSize);
        int totalCount = dynamicService.getTotalCount(keyword, author, status);
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        result.put("code", 200);
        result.put("data", dynamics);
        result.put("totalPages", totalPages);
        return result;
    }

    @PostMapping("/audit")
    public Map<String, Object> auditDynamic(
            @RequestParam("dynamicId") Long dynamicId,
            @RequestParam("newStatus") Integer newStatus,
            @RequestParam("auditorId") Long auditorId,
            @RequestParam("auditorName") String auditorName,
            @RequestParam(value = "auditReason", defaultValue = "") String auditReason) {
        Map<String, Object> result = new HashMap<>();
        boolean success = dynamicService.auditDynamic(dynamicId, newStatus, auditorId, auditorName, auditReason);
        result.put("code", success ? 200 : 500);
        result.put("message", success ? "审核成功" : "审核失败");
        return result;
    }
}